import 'package:flutter/material.dart';
import 'package:loading_indicator/loading_indicator.dart';
import 'package:yzb_flutter/global/application.dart';
import 'package:yzb_flutter/global/routers.dart';
import 'package:yzb_flutter/model/login_info_entity.dart';
import 'package:yzb_flutter/model/theme_entity.dart';
import 'package:yzb_flutter/utils/data_utils.dart';
import 'package:yzb_flutter/utils/utils.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool showPassword = false;

  String userName = '';
  String passWord = '';

  bool _loading = false;

  GlobalKey<FormState> _signInFormKey = GlobalKey();

  GlobalDimen mDimen = Application.mDimens;
  GlobalColor mColors = Application.mColors;

  @override
  Widget build(BuildContext context) {
    userName = ModalRoute.of(context).settings.arguments;
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      body: Container(
        color: Color(mColors.backgroundColor),
        child: Stack(
          children: <Widget>[
            Image.asset('assets/images/bg_login2.jpg',
                width: MediaQuery.of(context).size.width,
                height: MediaQuery.of(context).size.height,
                fit: BoxFit.fitHeight),
            Center(
                child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                buildLoginTitle(context),
                buildLoginForm(context),
                buildLoginBtn(context)
              ],
            ))
          ],
        ),
      ),
    );
  }

  ///登录框标题
  Container buildLoginTitle(BuildContext context) {
    return Container(
        width: MediaQuery.of(context).size.width * 0.8,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(8.0), topRight: Radius.circular(8.0)),
            gradient: LinearGradient(
              colors: [
                Color(Application.mColors.primaryColor),
                Color(Application.mColors.secondColor)
              ],
            )),
        child: Padding(
          padding: EdgeInsets.all(8.0),
          child: Center(
            child: Text(
              '登录',
              style: TextStyle(
                  fontSize: mDimen.titleSize,
                  decoration: TextDecoration.none,
                  color: Color(mColors.textColorWithPrimary)),
            ),
          ),
        ));
  }

  ///用户名和密码框
  Container buildLoginForm(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width * 0.8,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
            bottomLeft: Radius.circular(8.0),
            bottomRight: Radius.circular(8.0)),
        color: Color(mColors.transBgWhite),
      ),
      child: Column(
        children: <Widget>[
          Form(
            key: _signInFormKey,
            child: Column(
              children: <Widget>[
                Padding(
                    padding: EdgeInsets.only(left: 15, right: 15),
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          child: TextFormField(
                            decoration: InputDecoration(
                              hintText: '用户名',
                              border: InputBorder.none,
                              prefixIcon: Icon(
                                Icons.person_outline,
                                color: Color(mColors.primaryColor),
                              ),
                            ),
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return "用户名不能为空";
                              } else {
                                return null;
                              }
                            },
                            onSaved: (value) {
                              setState(() {
                                userName = value;
                              });
                            },
                          ),
                        ),
                        FlatButton(
                          child: Text(
                            '注册账号',
                            style: TextStyle(
                                decoration: TextDecoration.underline,
                                color: Color(mColors.primaryColor)),
                          ),
                          onPressed: showRegist,
                        )
                      ],
                    )),
                Container(
                  color: Colors.grey,
                  height: 1,
                  margin: EdgeInsets.only(left: 15, right: 15),
                ),
                Padding(
                    padding: EdgeInsets.only(left: 15, right: 15),
                    child: TextFormField(
                      obscureText: !showPassword,
                      decoration: InputDecoration(
                          hintText: '密码',
                          prefixIcon: Icon(
                            Icons.lock_outline,
                            color: Color(mColors.primaryColor),
                          ),
                          border: InputBorder.none,
                          suffixIcon: IconButton(
                            icon: Icon(
                              Icons.remove_red_eye,
                              color: showPassword
                                  ? Color(mColors.primaryColor)
                                  : Color(mColors.disableColor),
                            ),
                            onPressed: _showPassword,
                          )),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return "密码不能为空";
                        } else {
                          return null;
                        }
                      },
                      onSaved: (value) {
                        setState(() {
                          passWord = value;
                        });
                      },
                    )),
              ],
            ),
          )
        ],
      ),
    );
  }

  ///登录按钮
  Container buildLoginBtn(BuildContext context) {
    return Container(
        width: MediaQuery.of(context).size.width * 0.6,
        child: Column(
          children: <Widget>[
            GestureDetector(
              child: Container(
                  margin: EdgeInsets.only(top: 30.0),
                  decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: _loading
                          ? Color(mColors.textColorWithPrimary)
                          : Color(mColors.primaryColor),
                      border: Border.all(color: Colors.white, width: 1.0)),
                  child: Center(
                    child: Padding(
                      padding: EdgeInsets.all(12.0),
                      child: _loading
                          ? Container(
                        width: 29,
                        height: 29,
                        child: LoadingIndicator(
                            indicatorType: Indicator.lineSpinFadeLoader,
                            color: Color(mColors.primaryColor)),
                      )
                          : Text(
                        '→',
                        style: TextStyle(color: Colors.white, fontSize: 25.0),
                      ),
                    ),
                  )),
              onTap: doLogin,
            ),
            FlatButton(
              child: Text(
                '游客登录',
                style: TextStyle(
                    decoration: TextDecoration.underline,
                    color: Color(mColors.textColorWithPrimary)),
              ),
              onPressed: (){
                Application.mRouter.navigateTo(context, Routers.homePagePath,clearStack: true);
              },
              )
          ],
        ));
  }

  void _showPassword() {
    setState(() {
      showPassword = !showPassword;
    });
  }

  void doLogin() {
    if (_signInFormKey.currentState.validate()) {
      setState(() {
        _loading = true;
      });
      _signInFormKey.currentState.save();
      DataUtil.doLogin({'username': userName, 'password': passWord})
          .then((res) {
        setState(() {
          _loading = false;
        });
        if (res != null) {
          Utils.showToast("登录成功，欢迎${(res as LoginInfoEntity).nickname}");
        }
      });
    }
  }

  ///显示注册界面
  void showRegist() {
    Application.mRouter.navigateTo(context, Routers.registPagePath,clearStack: false);
  }
}
